<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>采购清单</title>
    <script src="../js/html2canvas.min.js"></script>
    <style>
        body { font-family: Arial, sans-serif; max-width: 900px; margin: 20px auto; padding: 0 15px; background-color: #fdf9fa; position: relative; }
        h1 { color: #e64398; text-align: center; margin-bottom: 25px; }
        .add-box { display: flex; gap: 10px; margin-bottom: 15px; align-items: center; flex-wrap: wrap; }
        #itemInput { flex: 3; min-width: 200px; padding: 12px; font-size: 16px; border: 2px solid #f1c4e3; border-radius: 8px; }
        #unitPriceInput { flex: 1; min-width: 80px; padding: 12px; font-size: 16px; border: 2px solid #f1c4e3; border-radius: 8px; }
        #quantityInput { flex: 1; min-width: 80px; padding: 12px; font-size: 16px; border: 2px solid #f1c4e3; border-radius: 8px; }
        #addBtn { padding: 12px 20px; background-color: #e64398; color: white; border: none; border-radius: 8px; cursor: pointer; white-space: nowrap; }
        #addBtn:hover { background-color: #d03183; }
        .list-header { display: flex; padding: 12px 15px; background-color: #e64398; color: white; border-radius: 8px 8px 0 0; font-weight: bold; }
        .header-index { width: 8%; text-align: center; }
        .header-name { width: 32%; }
        .header-unitPrice { width: 15%; text-align: center; }
        .header-quantity { width: 15%; text-align: center; }
        .header-totalPrice { width: 15%; text-align: center; }
        .header-status { width: 15%; text-align: center; }
        #list { list-style: none; padding: 0; margin: 0; border-top: none; }
        #list li { display: flex; align-items: center; padding: 12px 15px; margin: 0; background-color: #fff; border-bottom: 1px solid #f8f0f4; position: relative; transition: all 0.2s ease; }
        #list li:last-child { border-radius: 0 0 8px 8px; }
        #list li.checked .item-name { text-decoration: line-through; color: #999; }
        #list li:hover { background-color: #fef7fb; transform: translateX(2px); }
        .item-index { width: 8%; text-align: center; color: #666; }
        .item-name { width: 32%; word-break: break-all; }
        .item-unitPrice { width: 15%; text-align: center; }
        .item-quantity { width: 15%; text-align: center; }
        .item-totalPrice { width: 15%; text-align: center; color: #e64398; font-weight: 500; }
        .item-status { width: 15%; text-align: center; }
        .item-unitPrice input, .item-quantity input { width: 80%; padding: 6px; border: 1px solid #f1c4e3; border-radius: 4px; text-align: center; }
        .status-checkbox { width: 18px; height: 18px; cursor: pointer; }
        .deleteBtn { position: absolute; right: 25px; color: #ff4444; background: none; border: none; cursor: pointer; font-size: 18px; display: none; }
        #list li:hover .deleteBtn { display: block; }
        #exportBtn {
            position: fixed;
            right: 20px;
            top: 50%;
            transform: translateY(-50%);
            width: 50px;
            height: 50px;
            border-radius: 50%;
            background-color: #e64398;
            color: white;
            border: none;
            font-size: 14px;
            cursor: pointer;
            box-shadow: 0 3px 8px rgba(230,67,152,0.3);
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 5px;
            text-align: center;
            z-index: 10;
        }
        #exportBtn:hover { background-color: #d03183; }
        .summary-bar { display: flex; justify-content: flex-end; gap: 30px; padding: 15px; margin-top: 15px; background-color: #fff; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.05); }
        .summary-item { font-size: 16px; font-weight: bold; color: #e64398; }
        .summary-label { color: #666; font-weight: normal; margin-right: 5px; }
        .hide-on-export { transition: opacity 0.3s; }
        
        .toast {
            position: fixed;
            bottom: 20px;
            right: 20px;
            background-color: rgba(0, 0, 0, 0.7);
            color: white;
            padding: 12px 20px;
            border-radius: 8px;
            box-shadow: 0 3px 10px rgba(0, 0, 0, 0.2);
            z-index: 1000;
            opacity: 0;
            transform: translateY(20px);
            transition: all 0.3s ease;
            max-width: 300px;
        }
        
        .toast.show {
            opacity: 1;
            transform: translateY(0);
        }

        @media (max-width: 768px) {
            #exportBtn {
                position: fixed;
                right: 15px;
                bottom: 80px;
                top: auto;
                transform: none;
            }
            .summary-bar {
                flex-direction: column;
                gap: 10px;
                align-items: flex-end;
            }
            .header-index { width: 10%; }
            .header-name { width: 28%; }
            .header-unitPrice, .header-quantity, .header-totalPrice, .header-status { width: 16%; }
        }

        @media (max-width: 480px) {
            .add-box {
                flex-direction: column;
                align-items: stretch;
            }
            #itemInput, #unitPriceInput, #quantityInput, #addBtn {
                width: 100%;
                min-width: auto;
            }
        }
    </style>
</head>
<body>
    <h1 contenteditable="true">采购清单</h1>

    <div class="add-box hide-on-export">
        <input type="text" id="itemInput" placeholder="输入物品名称（如：喜糖盒子）">
        <input type="number" id="unitPriceInput" placeholder="单价（元）" min="0">
        <input type="number" id="quantityInput" placeholder="数量（份/个）" min="0" step="1">
        <button id="addBtn">添加</button>
    </div>

    <div class="list-header">
        <div class="header-index">序号</div>
        <div class="header-name">名称</div>
        <div class="header-unitPrice">单价（元）</div>
        <div class="header-quantity">数量</div>
        <div class="header-totalPrice">总价（元）</div>
        <div class="header-status">采购状态</div>
    </div>

    <ul id="list"></ul>

    <div class="summary-bar">
        <div class="summary-item">
            <span class="summary-label">总数量：</span>
            <span id="totalQuantity">0</span>
        </div>
        <div class="summary-item">
            <span class="summary-label">总金额：</span>
            <span id="totalAmount">0.00</span>元
        </div>
    </div>

    <button id="exportBtn" class="hide-on-export">导出</button>
    
    <!-- 提示模态框 -->
    <div id="toast" class="toast"></div>

    <script>
        const input = document.getElementById('itemInput');
        const unitPriceInput = document.getElementById('unitPriceInput');
        const quantityInput = document.getElementById('quantityInput');
        const addBtn = document.getElementById('addBtn');
        const list = document.getElementById('list');
        const exportBtn = document.getElementById('exportBtn');
        const totalQuantityEl = document.getElementById('totalQuantity');
        const totalAmountEl = document.getElementById('totalAmount');
        const hideOnExportEls = document.querySelectorAll('.hide-on-export');
        const toast = document.getElementById('toast');

        const defaultPreWeddingItems = [
            { text: '新郎礼服（西装+衬衫+领带）', unitPrice: '', quantity: '1', checked: false },
            { text: '新娘主婚纱', unitPrice: '', quantity: '1', checked: false },
            { text: '新娘敬酒服', unitPrice: '', quantity: '1', checked: false },
            { text: '婚鞋（新娘高跟鞋）', unitPrice: '', quantity: '1', checked: false },
            { text: '婚鞋（新郎皮鞋）', unitPrice: '', quantity: '1', checked: false },
            { text: '结婚对戒', unitPrice: '', quantity: '1', checked: false },
            { text: '喜糖（每盒）', unitPrice: '', quantity: '50', checked: false },
            { text: '婚礼请柬', unitPrice: '', quantity: '50', checked: false },
            { text: '婚房喜字（大+小）', unitPrice: '', quantity: '10', checked: false },
            { text: '婚房气球', unitPrice: '', quantity: '2', checked: false },
            { text: '喜烟（每条）', unitPrice: '', quantity: '10', checked: false },
            { text: '喜酒（每瓶）', unitPrice: '', quantity: '20', checked: false },
            { text: '婚礼红包（2元面额）', unitPrice: '2', quantity: '30', checked: false }
        ];

        // 初始化数据（带本地存储兼容处理）
        let preWeddingItems = [];
        try {
            let storedItems = localStorage.getItem('preWeddingShoppingList');
            preWeddingItems = storedItems ? JSON.parse(storedItems) : JSON.parse(JSON.stringify(defaultPreWeddingItems));
        } catch (e) {
            preWeddingItems = JSON.parse(JSON.stringify(defaultPreWeddingItems));
            showToast('读取本地存储失败，使用默认列表');
            console.warn('读取本地存储失败，使用默认列表：', e);
        }

        // 显示提示模态框
        function showToast(message, duration = 3000) {
            toast.textContent = message;
            toast.classList.add('show');
            
            clearTimeout(toast.timeout);
            toast.timeout = setTimeout(() => {
                toast.classList.remove('show');
            }, duration);
        }

        // 计算单项总价
        function calculateItemTotal(unitPrice, quantity) {
            const price = Number(unitPrice) || 0;
            const count = Number(quantity) || 0;
            return price * count;
        }

        // 计算汇总信息
        function calculateSummary() {
            let totalQuantity = 0;
            let totalAmount = 0;

            preWeddingItems.forEach(item => {
                const count = Number(item.quantity) || 0;
                const amount = calculateItemTotal(item.unitPrice, item.quantity);
                totalQuantity += count;
                totalAmount += amount;
            });

            totalQuantityEl.textContent = totalQuantity;
            totalAmountEl.textContent = totalAmount.toFixed(2);
        }

        // 渲染列表
        function renderItems() {
            list.innerHTML = '';
            preWeddingItems.forEach((item, index) => {
                const li = document.createElement('li');
                if (item.checked) li.classList.add('checked');
                const itemTotal = calculateItemTotal(item.unitPrice, item.quantity);

                // 序号
                const indexDiv = document.createElement('div');
                indexDiv.className = 'item-index';
                indexDiv.textContent = index + 1;

                // 名称
                const nameDiv = document.createElement('div');
                nameDiv.className = 'item-name';
                nameDiv.textContent = item.text;

                // 单价
                const unitPriceDiv = document.createElement('div');
                unitPriceDiv.className = 'item-unitPrice';
                const upInput = document.createElement('input');
                upInput.type = 'number';
                upInput.placeholder = '0';
                upInput.value = item.unitPrice || '';
                upInput.min = 0;
                upInput.addEventListener('input', (e) => {
                    const value = e.target.value.trim();
                    preWeddingItems[index].unitPrice = value;
                    saveItems();
                    renderItems();
                });
                unitPriceDiv.appendChild(upInput);

                // 数量
                const quantityDiv = document.createElement('div');
                quantityDiv.className = 'item-quantity';
                const qInput = document.createElement('input');
                qInput.type = 'number';
                qInput.placeholder = '0';
                qInput.value = item.quantity || '';
                qInput.min = 0;
                qInput.step = 1;
                qInput.addEventListener('input', (e) => {
                    const value = e.target.value.trim();
                    preWeddingItems[index].quantity = value;
                    saveItems();
                    renderItems();
                });
                quantityDiv.appendChild(qInput);

                // 总价
                const totalPriceDiv = document.createElement('div');
                totalPriceDiv.className = 'item-totalPrice';
                totalPriceDiv.textContent = itemTotal === 0 ? '—' : itemTotal.toFixed(2);

                // 状态
                const statusDiv = document.createElement('div');
                statusDiv.className = 'item-status';
                const checkbox = document.createElement('input');
                checkbox.type = 'checkbox';
                checkbox.className = 'status-checkbox';
                checkbox.checked = item.checked;
                checkbox.addEventListener('change', () => {
                    preWeddingItems[index].checked = checkbox.checked;
                    li.classList.toggle('checked', checkbox.checked);
                    saveItems();
                    calculateSummary();
                    showToast(checkbox.checked ? '已标记为已采购' : '已标记为未采购');
                });
                statusDiv.appendChild(checkbox);

                // 删除按钮
                const deleteBtn = document.createElement('button');
                deleteBtn.className = 'deleteBtn';
                deleteBtn.innerHTML = '&#10006;';
                deleteBtn.addEventListener('click', (e) => {
                    e.stopPropagation();
                    const deletedItem = preWeddingItems[index].text;
                    preWeddingItems.splice(index, 1);
                    saveItems();
                    renderItems();
                    showToast(`已删除：${deletedItem}`);
                });

                // 组装列表项
                li.appendChild(indexDiv);
                li.appendChild(nameDiv);
                li.appendChild(unitPriceDiv);
                li.appendChild(quantityDiv);
                li.appendChild(totalPriceDiv);
                li.appendChild(statusDiv);
                li.appendChild(deleteBtn);
                list.appendChild(li);
            });
        }

        // 保存数据到本地存储
        function saveItems() {
            try {
                localStorage.setItem('preWeddingShoppingList', JSON.stringify(preWeddingItems));
                calculateSummary();
            } catch (e) {
                console.warn('本地存储失败，数据可能无法保存：', e);
                showToast('浏览器存储功能受限，数据无法持久化保存');
            }
        }

        // 导出长图功能
        function exportImage() {
            // 隐藏导出时不需要的元素
            hideOnExportEls.forEach(el => el.style.opacity = '0');
            
            // 延迟执行以确保样式生效
            setTimeout(() => {
                html2canvas(document.body, {
                    scale: 2, // 提高清晰度
                    useCORS: true,
                    logging: false,
                    windowWidth: document.body.scrollWidth,
                    windowHeight: document.body.scrollHeight
                }).then(canvas => {
                    // 恢复元素显示
                    hideOnExportEls.forEach(el => el.style.opacity = '1');
                    
                    // 创建下载链接
                    const link = document.createElement('a');
                    link.download = '采购清单_' + new Date().toLocaleDateString() + '.png';
                    link.href = canvas.toDataURL('image/png');
                    link.click();
                    
                    showToast('导出成功！');
                }).catch(err => {
                    hideOnExportEls.forEach(el => el.style.opacity = '1');
                    showToast('导出失败，请重试！');
                    console.error('导出错误：', err);
                });
            }, 300);
        }

        // 绑定添加按钮事件
        addBtn.addEventListener('click', () => {
            const text = input.value.trim();
            const unitPrice = unitPriceInput.value.trim();
            const quantity = quantityInput.value.trim();
            
            if (!text) {
                showToast('请输入物品名称！');
                return;
            }
            
            preWeddingItems.push({
                text,
                unitPrice,
                quantity: quantity || '1',
                checked: false
            });
            
            // 清空输入框
            input.value = '';
            unitPriceInput.value = '';
            quantityInput.value = '';
            
            saveItems();
            renderItems();
            showToast(`已添加：${text}`);
            // 聚焦到物品名称输入框
            input.focus();
        });

        // 绑定导出按钮事件
        exportBtn.addEventListener('click', exportImage);

        // 绑定回车添加事件
        document.querySelectorAll('#itemInput, #unitPriceInput, #quantityInput').forEach(el => {
            el.addEventListener('keypress', (e) => {
                if (e.key === 'Enter') addBtn.click();
            });
        });

        // 初始化页面
        renderItems();
        calculateSummary();
    </script>
</body>
</html>